package com.aoip.telemetry.telemetry.receive.message.common;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageCodec;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * 需结合帧解码器使用
 * bytebuf 与 字符串的相互转换
 *
 * @author chenbai
 * @version 1.0
 * @date 2022/2/28 11:01
 */
@ChannelHandler.Sharable
@Slf4j
public class AsciiMessageCodecSharable extends MessageToMessageCodec<ByteBuf, String> {

    /**
     * 编码：将字符串写入到消息通道
     *
     * @author chenbai
     * @date 2022/2/28
     **/
    @Override
    protected void encode(ChannelHandlerContext ctx, String msg, List<Object> out)  {
        ByteBuf byteBuf = ctx.alloc().buffer();
        byteBuf.writeBytes(msg.getBytes(StandardCharsets.UTF_8));
        out.add(byteBuf);
    }

    /**
     * 解码：将接收到的报文转为字符串
     *
     * @author chenbai
     * @date 2022/2/28
     **/
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf byteBuf, List<Object> out) {
        int allLength = byteBuf.readableBytes();
        byte[] bytes = new byte[allLength];
        byteBuf.readBytes(bytes, 0, allLength);
        String hexString = new String(bytes, StandardCharsets.UTF_8).toUpperCase();
        out.add(hexString);
    }
}
